package com.fang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fang.common.cache.RedisCacheEnum;
import com.fang.entity.SysMenu;
import com.fang.entity.SysRole;
import com.fang.entity.SysUser;
import com.fang.mapper.SysUserMapper;
import com.fang.service.SysMenuService;
import com.fang.service.SysRoleService;
import com.fang.service.SysUserService;
import com.fang.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Fang Ruichuan
 * @since 2022-08-27
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysMenuService sysMenuService;

    @Override
    public SysUser getByUsername(String username) {
        return getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, username));
    }

    /**
     * 获取用户权限信息
     * @author Fang Ruichuan
     * @date 2022/9/4 16:27
     * @param userId
     * @return String
     */
    @Override
    public String getUserAuthorityInfo(Long userId) {
        SysUser sysUser = sysUserMapper.selectById(userId);
        // 角色(ROLE_admin)、菜单操作权限(sys:user:list)
        String authority = "";
        if (RedisUtil.KeyOps.hasKey(RedisCacheEnum.USER_AUTHORITY_INFO.getValue() + ":" + sysUser.getUsername())) {
            return RedisUtil.StringOps.get(RedisCacheEnum.USER_AUTHORITY_INFO.getValue() + ":" + sysUser.getUsername());
        } else {
            // 获取角色编码
            List<SysRole> roles = sysRoleService.list(new QueryWrapper<SysRole>()
                    .inSql("id", "select role_id from sys_user_role where user_id = " + userId));
            if (!CollectionUtils.isEmpty(roles)) {
                String roleCodes = roles.stream().map(r -> "ROLE_" + r.getCode()).collect(Collectors.joining(","));
                authority = roleCodes.concat(",");
            }
            // 获取菜单操作编码
            List<Long> menuIds = sysUserMapper.getNavMenuIds(userId);
            if (!CollectionUtils.isEmpty(menuIds)) {
                List<SysMenu> menus = sysMenuService.listByIds(menuIds);
                String menuPerms = menus.stream().map(SysMenu::getPerms).collect(Collectors.joining(","));
                authority = authority.concat(menuPerms);
            }
            RedisUtil.StringOps.setEx(RedisCacheEnum.USER_AUTHORITY_INFO.getValue() + ":" + sysUser.getUsername(),
                    authority, RedisCacheEnum.USER_AUTHORITY_INFO.getTime(), TimeUnit.SECONDS);
            return authority;
        }
    }

    @Override
    public void clearUserAuthorityInfo(String username) {
        RedisUtil.KeyOps.delete(RedisCacheEnum.USER_AUTHORITY_INFO.getValue() + ":" + username);
    }

    @Override
    public void clearUserAuthorityInfoByRoleId(Long roleId) {
        List<SysUser> sysUsers = this.list(new QueryWrapper<SysUser>()
                .inSql("id", "select user_id from sys_user_role where role_id = " + roleId));
        Optional.ofNullable(sysUsers).orElse(new ArrayList<>()).forEach(u -> this.clearUserAuthorityInfo(u.getUsername()));
    }

    @Override
    public void clearUserAuthorityInfoByMenuId(Long menuId) {
        List<SysUser> sysUsers = sysUserMapper.listByMenuId(menuId);
        Optional.ofNullable(sysUsers).orElse(new ArrayList<>()).forEach(u -> this.clearUserAuthorityInfo(u.getUsername()));
    }
}
